<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\enum\CommonEnum;
use app\enum\OceanEnum;
use app\model\AccountDailyStatModel;
use app\model\CrontabTaskModel;
use app\model\KsAdvertiserDailyStatModel;
use app\model\OeAdvertiserDailyStatModel;
use app\model\QqAdvertiserDailyStatModel;
use app\service\CrontabTaskService;
use app\service\stat\daily\AccountService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class AccountDailyStatWork extends BaseWork implements DailyStatWork
{
    public string $tag;

    public array $clientAccountInfo = [];

    /**
     * 设置任务标识.
     * @param mixed $tag
     */
    public function setTag($tag = ''): bool
    {
        if (! is_null($tag)) {
            $this->tag = strval($tag);
        }
        return true;
    }

    /**
     * 获取任务标识.
     */
    public function getTag(): string
    {
        return $this->tag;
    }

    /**
     * 获取脚本名.
     */
    public function getCommandName(): string
    {
        return $this->getName();
    }

    /**
     * 获取定时任务.
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCrontabTaskInfo(): CrontabTaskModel
    {
        $where = [
            ['task_name', '=', $this->getName()],
            ['tag', '=', $this->getTag()],
        ];

        $obj = new CrontabTaskModel();
        $model = $obj->where($where)->field(true)->find();
        return $model instanceof CrontabTaskModel ? $model : $obj;
    }

    protected function configure()
    {
        // 指令配置
        $this->setName('account_daily_stat_work');
        $this->setDescription('流水汇总');
        $this->addArgument('type', Argument::REQUIRED, '类型  1：昨日报表 2：自定义时间');
        $this->addArgument('media_id', Argument::REQUIRED, '媒体id');
        $this->addArgument('start_date', Argument::OPTIONAL, '开始日期');
        $this->addArgument('end_date', Argument::OPTIONAL, '结束日期');
        $this->addArgument('advertiser_id', Argument::OPTIONAL, '账户id');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');

        $output->writeln('=======流水汇总开始' . date('Y-m-d H:i:s', time()) . '=======');
        $type = $input->getArgument('type');
        $mediaId = intval($input->getArgument('media_id'));
        $this->setTag($mediaId);
        $startDate = $input->getArgument('start_date');
        $endDate = $input->getArgument('end_date');
        $advertiserId = $input->getArgument('advertiser_id') ?: '';
        // 默认昨日
        if ($type == OceanEnum::YESTERDAY) {
            // 获取凌晨的时间戳
            $time = strtotime(date('Y-m-d 00:00:00'));
            // 如果已执行，就不跑了
            //            if ($this->getCrontabTaskInfo()->finish_time > $time) {
            //                exit;
            //            }
            //            if ($mediaId == CommonEnum::OE_MEDIA) {
            //                $keyWord = 'oe_advertiser_daily_stat_work';
            //            } elseif ($mediaId == CommonEnum::KS_MEDIA) {
            //                $keyWord = 'ks_advertiser_daily_stat_work';
            //            } elseif ($mediaId == CommonEnum::QQ_MEDIA) {
            //                $keyWord = 'qq_advertiser_daily_stat_work';
            //            } else {
            //                exit;
            //            }
            //            $isOk = CrontabTaskModel::where('task_name', $keyWord)
            //                ->where('finish_time', '>', $time)
            //                ->find();
            //            if (! $isOk) {
            //                exit;
            //            }
            // 判断是否已经执行
            //            $isDone = TaskAccountService::isTodayTaskDone(ServiceCostEnum::TASK_TYPE_ACCOUNT, $mediaId, intval($startDate));
            //            if (! $isDone) {
            //                exit;
            //            }
        }
        if ($type == OceanEnum::YESTERDAY) {
            $yesterDay = date('Ymd', strtotime('-1 day'));
            $startDate = $yesterDay;
            $endDate = $yesterDay;
        } elseif ($type == OceanEnum::CUSTOM_DAY) {
            if (! $startDate || ! $endDate) {
                $output->writeln('===========开始时间，结束时间都必须存在！===========');
                return;
            }

            if ($startDate > $endDate) {
                $output->writeln('===========开始时间必须小于结束时间！===========');
                return;
            }
        } elseif ($type == 3) {
            // 三天前，前天
            $yesterDay = date('Ymd', strtotime('-3 day'));
            $startDate = $yesterDay;
            $endDate = $yesterDay;
        }

        if ($startDate != $endDate && $mediaId == 2) {
            $dates = createDateRange(date('Y-m-d', strtotime("{$startDate}")), date('Y-m-d', strtotime("{$endDate}")));
            try {
                $accountService = new AccountService();
                foreach ($dates as $date) {
                    $date = date('Ymd', strtotime($date));
                    $dataList = self::getStatList($mediaId, intval($date), intval($date), $advertiserId);
                    if ($dataList) {
                        foreach ($dataList as $data) {
                            $accountService->setData($data);
                            $res = $accountService->saveStatData();
                            if (! $res) {
                                $output->writeln('===========失败:' . $accountService->getError(0) . '===========');
                            }
                        }
                    }
                }
            } catch (\Exception $e) {
                $output->writeln('===========失败:' . $e->getMessage() . date('Y-m-d H:i:s', time()) . '===========');
            }
        } else {
            $dataList = self::getStatList($mediaId, intval($startDate), intval($endDate), $advertiserId);
            if ($dataList) {
                $model = new AccountDailyStatModel();
                $accountService = new AccountService();
                try {
                    foreach ($dataList as $data) {
                        $accountService->setData($data);
                        $res = $accountService->saveStatData($model);
                        if (! $res) {
                            $output->writeln('===========失败:' . $accountService->getError(0) . '===========');
                        }
                    }
                    if ($type == 1) {
                        // 更新任务状态
                        CrontabTaskService::setSingleTask($this);
                    }
                } catch (\Exception $e) {
                    $output->writeln('===========失败:' . $e->getMessage() . date('Y-m-d H:i:s', time()) . '===========');
                }
            }
        }
        $output->writeln('=======流水汇总结束' . date('Y-m-d H:i:s', time()) . '=======');
        $output->writeln('success');
    }

    /**
     * 获取指定流水数据.
     */
    private function getStatList(int $mediaId, int $startDate, int $endDate, string $advertiserId = '')
    {
        $data = [];
        $where[] = [
            ['stat_date', 'between', [$startDate, $endDate]],
        ];
        if ($advertiserId) {
            $where[] = ['advertiser_id', '=', $advertiserId];
        }
        if ($mediaId == CommonEnum::OE_MEDIA) {
            $data = OeAdvertiserDailyStatModel::where($where)->select();
            // $data = OeAdvertiserDailyStatModel::where($where)->where('advertiser_id', '1724980916238350')->select(); // test
        } elseif ($mediaId == CommonEnum::KS_MEDIA) {
            $data = KsAdvertiserDailyStatModel::where($where)->select();
        } elseif ($mediaId == CommonEnum::QQ_MEDIA) {
            $data = QqAdvertiserDailyStatModel::where($where)->field('*,sum(cost) as cost,sum(cash_cost) as cash_cost,sum(reward_cost) as reward_cost,sum(balance) as balance')->group('advertiser_id,stat_date')->select();
        }
        return $data;
    }
}
